from django.http import HttpResponse, Http404
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from forms import UserImageForm
from models import UserImage, NullObj
import os, time, md5
from ihlj import settings
from django.utils import simplejson

@csrf_protect
@login_required
def upload_image(request, next=None, using=None):
    if request.method == 'GET':
        form = UserImageForm()
        return render(request, "image/upload.html", {"imgform":form})

    form = UserImageForm(request.POST, request.FILES) 
    if form.security_errors():
        print form.security_errors
        raise Http404

    if form.errors:
        return render(request, "image/upload.html", {"imgform":form})


    #redirect_to = request.POST.get("redirect_to", "")
    #content_type_id = request.POST.get(""
    #related_object_id = request.POST.get("related_object_id", "")

    f = request.FILES["userimage"]  
    ext = os.path.splitext(f.name)[1]
    tmp = md5.new(f.name)
    tmp.update(str(time.time()))
    fn = tmp.hexdigest()
    os.makedirs(os.path.join(settings.MEDIA_ROOT, fn[0], fn[1]))
    relative_path = os.path.join(fn[0], fn[1], fn[2:] + ext)
    path = os.path.join(settings.MEDIA_ROOT, relative_path)
    fp = open(path, "ab")
    for trunk in f.chunks():
        fp.write(trunk)
    fp.close()
    
    image = UserImage()
    image.ip_address = request.META.get("REMOTE_ADDR", None)
    image.user = request.user
    image.path = relative_path
    image.size = f.size
    obj = NullObj.objects.getcacheobj()
    image.content_object = obj 
    image.save()

    form = UserImageForm()
    return render(request, "image/upload.html", {"imgform":form, "image":image})


@login_required
def upload_test(request):
    return render(request, "image/test.html")


